﻿using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Reflection;
using System;
using System.Linq;

namespace Framework.Repository
{
    public partial class FrameworkContext : DbContext
    {
        /*
         * T4代码生成器：http://www.cnblogs.com/guomingfeng/p/mvc-ef-t4.html
         * 需要两个插件：
         * 1.Devart T4 Editor：智能提示
         * 2.T4 Toolbox：生成多文件
         */

        public FrameworkContext()
            : base("Name=MVCFramework")
        {
            Database.SetInitializer<FrameworkContext>(null);//从不创建数据库

            this.Configuration.ProxyCreationEnabled = false;
            this.Configuration.LazyLoadingEnabled = false;//禁用延迟加载
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //移除一对多的级联删除约定，需要级联删除可以在Map类里单独开启：.WillCascadeOnDelete(true)
            //modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

            //多对多启用级联删除约定，不想级联删除可以在删除前判断关联的数据进行拦截
            //modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();

            //通过反射一次性将所有表进行映射
            var typesToRegister = Assembly.GetExecutingAssembly().GetTypes()
                                 .Where(type => !String.IsNullOrEmpty(type.Namespace))
                                 .Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));
            foreach (var type in typesToRegister)
            {
                dynamic configurationInstance = Activator.CreateInstance(type);
                modelBuilder.Configurations.Add(configurationInstance);
            }
        }

    }
}
